<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="form" :model="search" label-width="80px" :inline="true">
        <el-form-item label="设备编号:">
          <el-input
            v-model="search.innerCode"
            clearable
            placeholder="请输入"
            size="medium"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="my-primary1"
            icon="el-icon-search"
            size="medium"
            @click="query"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="result">
      <el-row type="flex" class="operation">
        <el-button
          type="primary"
          class="my-primary2"
          icon="el-icon-circle-plus-outline"
          @click="showAdd('add')"
        >新建</el-button>
        <el-button
          class="my-secondary"
          @click="batchOperate"
        >批量操作</el-button>
      </el-row>
      <el-table
        :data="tableData"
        style="width: 100%"
        empty-text="暂无数据"
        fit
        highlight-current-row
        :cell-style="{
          height: '44px',
          padding: '2px 0px',
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
        :header-cell-style="{
          lineHeight: 1.15,
          padding: '10px 0px 9px',
          background: 'rgb(243, 246, 251)',
          fontWeight: 500,
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          type="index"
          :index="(index) => (search.pageIndex - 1) * 10 + (index + 1)"
          label="序号"
          width="80px"
        />
        <el-table-column prop="innerCode" label="设备编号" />
        <el-table-column prop="type.name" label="设备型号" />
        <el-table-column label="详细地址">
          <template v-slot="{ row }">
            {{ row.node.addr.substring(row.node.addr.lastIndexOf("-") + 1) }}
          </template>
        </el-table-column>
        <el-table-column prop="ownerName" label="合作商" />
        <el-table-column label="设备状态">
          <template v-slot="{ row }">
            {{
              row.vmStatus === 0
                ? "未投放"
                : row.vmStatus === 1
                  ? "运营"
                  : "撤机"
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="{ row }">
            <el-button
              type="text"
              class="el-button--primary-text"
              @click.native="showChannelInfo(row)"
            >
              货道
            </el-button>
            <el-button
              type="text"
              class="el-button--primary-text"
              @click.native="showPolicy(row.innerCode)"
            >
              策略
            </el-button>
            <el-button
              type="text"
              class="el-button--primary-text"
              @click.native="showEdit(row)"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          layout="slot,prev,next"
          :current-page.sync="search.pageIndex"
          :total="totalCount"
          :page-size="search.pageSize"
          prev-text="上一页"
          next-text="下一页"
          @current-change="vmSearch"
        >
          <template order="-1">
            <span
              class="el-pagination__total"
            >共{{ totalCount }}条记录 第 {{ search.pageIndex }}/{{
              totalPage
            }}
              页</span>
          </template>
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="新增设备"
      :visible.sync="addDialog"
      width="630px"
      top="15vh"
      @close="addClose"
    >
      <el-form
        ref="add"
        :model="addForm"
        :rules="addRules"
        label-width="140px"
        size="medium"
      >
        <el-form-item label="设备编号："> 系统自动生成 </el-form-item>
        <el-form-item label="选择型号：" prop="vmType">
          <el-select
            v-model="addForm.vmType"
            clearable
            placeholder="请选择"
            style="width: 396px"
          >
            <el-option
              v-for="item in vmTypeList"
              :key="item.typeId"
              :label="item.name"
              :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择点位：" prop="nodeId">
          <el-select
            v-model="addForm.nodeId"
            clearable
            placeholder="请选择"
            style="width: 396px"
          >
            <el-option
              v-for="item in nodeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="16">
              <el-button class="my-secondary" @click="addClose">取消</el-button>
              <el-button
                type="primary"
                class="my-primary2"
                @click="addSubmit"
              >确认</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="批量策略管理"
      :visible.sync="batchDialog"
      width="630px"
      top="15vh"
      @close="batchClose"
    >
      <el-form
        ref="batch"
        :model="batchForm"
        :rules="batchRules"
        label-width="140px"
        size="medium"
      >
        <el-form-item label="选择策略：" prop="policyId">
          <el-select
            v-model="batchForm.policyId"
            clearable
            placeholder="请选择"
            style="width: 396px"
          >
            <el-option
              v-for="item in policyList"
              :key="item.policyId"
              :label="item.policyName"
              :value="item.policyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="16">
              <el-button
                class="my-secondary"
                @click="batchClose"
              >取消</el-button>
              <el-button
                type="primary"
                class="my-primary2"
                @click="batchSubmit"
              >确认</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="策略管理"
      :visible.sync="policyDialog"
      width="630px"
      @close="policyClose"
    >
      <el-form :model="policy" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="机器编号：">{{ policy.vmId }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="策略名称：">{{
              policy.policyName
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="策略方案：">{{
              policy.discount + "%"
            }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-dialog
      title="修改设备"
      :visible.sync="editDialog"
      width="630px"
      top="15vh"
      @close="editClose"
    >
      <el-form ref="edit" :model="editForm" label-width="140px" size="medium">
        <el-form-item label="机器编号："> {{ vmInfo.innerCode }} </el-form-item>
        <el-form-item label="供货时间：">
          {{ formattedDate(vmInfo.lastSupplyTime) }}
        </el-form-item>
        <el-form-item label="设备类型：">
          {{ vmInfo.type?.name }}
        </el-form-item>
        <el-form-item label="设备容量：">
          {{ vmInfo.node?.vmCount }}
        </el-form-item>
        <el-form-item label="设备点位：" prop="nodeId">
          <el-select
            v-model="editForm.nodeId"
            clearable
            placeholder="请选择"
            style="width: 396px"
          >
            <el-option
              v-for="item in nodeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合作商："> {{ vmInfo.ownerName }} </el-form-item>
        <el-form-item label="所属区域：">
          {{ vmInfo.region?.name }}
        </el-form-item>
        <el-form-item label="设备地址：">
          {{
            vmInfo.node?.addr.substring(vmInfo.node?.addr.lastIndexOf("-") + 1)
          }}
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="16">
              <el-button
                class="my-secondary"
                @click="editClose"
              >取消</el-button>
              <el-button
                type="primary"
                class="my-primary2"
                @click="editSubmit"
              >确认</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="货道设置"
      :visible.sync="channelInfoDialog"
      width="940px"
      style="margin-top:-60px"
      @close="channelInfoClose"
    >
      <div class="vm-config-channel-dialog-wrapper">
        <div class="channel-basic">
          <span class="vm-row">货道行数：{{ channelInfo.length }}</span>
          <span class="vm-col">货道列数：{{ channelInfo[0]?.length }}</span>
          <span class="channel-max-capacity">货道容量（个）：10</span>
          <el-button
            type="primary"
            class="my-primary1"
            style="margin-right: 22px"
            @click="showTop10()"
          >智能排货</el-button>
        </div>
        <el-scrollbar class="scrollbar">
          <el-row
            v-for="(item, index) in channelInfo"
            :key="index"
            type="flex"
            class="space"
            :style="{transform: transform}"
          >
            <el-col v-for="it,ind in item" :key="it.channelId" :span="12" style="padding-left: 8px; padding-right: 8px;">
              <div class="item">
                <div class="code">{{ it.channelCode }}</div>
                <div v-if="it.sku" class="sku">
                  <img :src="it.sku.skuImage" class="img">
                  <div :title="it.sku?.skuName" class="name">
                    {{ it.sku.skuName }}
                  </div>
                </div>
                <div v-else class="sku">
                  <img
                    src=""
                    class="img"
                  >
                  <div title="暂无商品" class="name">
                    暂无商品
                  </div>
                </div>
                <div>
                  <el-button
                    type="text"
                    class="el-button--primary-text"
                    @click.native="addChannel(index,ind)"
                  >
                    添加
                  </el-button>
                  <el-button
                    :disabled="it.sku === null"
                    type="text"
                    class="el-button--danger-text"
                    @click.native="delChannel(index,ind)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-scrollbar>
        <svg version="1.1" viewBox="0 0 1024 1024" class="arrow arrow-left svg-icon svg-fill" :class="{ disabled: transform !== 'translateX(-102%)' }" style="width: 16px; height: 16px;" @click="slider('0')"><defs /><path pid="0" d="M398.182 522.214a23.398 23.398 0 0 1-32 8.55 23.373 23.373 0 0 1-8.55-32L627.046 32.078A23.45 23.45 0 0 1 667.622 55.5l-269.44 466.713zm270.08 443.75a23.398 23.398 0 1 1-40.499 23.553l-270.797-465.92a23.424 23.424 0 0 1 40.5-23.552l270.796 465.92z" /></svg>
        <svg version="1.1" viewBox="0 0 1024 1024" class="arrow arrow-right svg-icon svg-fill" :class="{ disabled: transform === 'translateX(-102%)' }" style="width: 16px; height: 16px;" @click="slider('-102%')"><defs /><path pid="0" d="M618.857 522.214a23.398 23.398 0 0 0 32 8.55 23.373 23.373 0 0 0 8.576-32L389.993 32.103a23.45 23.45 0 0 0-40.576 23.424l269.44 466.688zm-270.08 443.75a23.398 23.398 0 1 0 40.499 23.553l270.822-465.92a23.424 23.424 0 0 0-40.499-23.552L348.751 966.016z" /></svg>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            class="my-primary2"
            @click="confirmChannel()"
          >确认</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="选择商品"
      :visible.sync="chooseGoodDialog"
      width="858px"
      @close="chooseGoodClose"
    >
      <div class="vm-select-sku-dialog-wrapper">
        <el-form label-width="85px" class="search">
          <el-form-item label="商品名称：">
            <el-row type="flex" justify="space-between">
              <el-col>
                <el-input v-model="skuForm.skuName" class="sku-name" size="medium" placeholder="请输入" />
              </el-col>
              <el-col>
                <el-button
                  type="primary"
                  class="my-primary1"
                  icon="el-icon-search"
                  @click="queryGood"
                >查询</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <el-row
          style="margin-left: -10px; margin-right: -10px;"
        >
          <el-col v-for="item,index in skuList" :key="item.skuId" :span="5" style="padding-left: 10px; padding-right: 10px;">
            <div class="item">
              <div class="sku space" @click="chooseGood(index)">
                <img v-show="item.isShow" src="" class="selected">
                <img :src="item.skuImage" class="img">
                <div :title="item.skuName" class="name">
                  {{ item.skuName }}
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <svg version="1.1" viewBox="0 0 1024 1024" class="arrow arrow-left svg-icon svg-fill" :class="{ disabled: skuForm.pageIndex === 1 }" style="width: 16px; height: 16px;" @click="prevPage"><defs /><path pid="0" d="M398.182 522.214a23.398 23.398 0 0 1-32 8.55 23.373 23.373 0 0 1-8.55-32L627.046 32.078A23.45 23.45 0 0 1 667.622 55.5l-269.44 466.713zm270.08 443.75a23.398 23.398 0 1 1-40.499 23.553l-270.797-465.92a23.424 23.424 0 0 1 40.5-23.552l270.796 465.92z" /></svg>
        <svg version="1.1" viewBox="0 0 1024 1024" class="arrow arrow-right svg-icon svg-fill" :class="{ disabled: skuForm.pageIndex === skuTotalPage }" style="width: 16px; height: 16px;" @click="nextPage"><defs /><path pid="0" d="M618.857 522.214a23.398 23.398 0 0 0 32 8.55 23.373 23.373 0 0 0 8.576-32L389.993 32.103a23.45 23.45 0 0 0-40.576 23.424l269.44 466.688zm-270.08 443.75a23.398 23.398 0 1 0 40.499 23.553l270.822-465.92a23.424 23.424 0 0 0-40.499-23.552L348.751 966.016z" /></svg>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            class="my-primary2"
            @click="confirmChoose()"
          >确认</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="智能排货"
      :visible.sync="top10Dialog"
      width="858px"
      @close="top10Close"
    >
      <div class="vm-top10-sku-dialog-wrapper">
        <div class="tips">
          该区域属于{{ business.node?.businessType.name }}商圈适合销售以下商品：
        </div>
        <el-row
          style="margin-left: -10px; margin-right: -10px;"
        >
          <el-col v-for="item,index in top10List" :key="item.skuId" :span="5" style="padding-left: 10px; padding-right: 10px;">
            <div class="item">
              <div class="sku space" @click="chooseGood(index)">
                <img :src="item.image" class="img">
                <div :title="item.skuName" class="name">
                  {{ item.skuName }}
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            class="my-primary2"
            @click="confirmTop10()"
          >采纳建议</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchVmList,
  addVm,
  searchVmType,
  getPolicyList,
  applyPolicy,
  getVmPolicy,
  getChannelInfo,
  searchNode,
  editVmNode,
  searchSku,
  getBusinessTop10,
  updateChannel
} from '@/api/vm'
import _ from 'lodash'
export default {
  data() {
    return {
      search: {
        innerCode: '',
        pageIndex: 1,
        pageSize: 10,
        status: null
      },
      tableData: [],
      totalCount: 0,
      totalPage: 0,
      addDialog: false,
      addForm: {
        nodeId: '',
        vmType: '',
        createUserId: this.$store.getters.userId
      },
      addRules: {
        nodeId: [{ required: true, message: '请选择', trigger: 'change' }],
        vmType: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      batchForm: {
        innerCodeList: [],
        policyId: ''
      },
      batchRules: {
        policyId: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      batchDialog: false,
      channelInfoDialog: false,
      vmInfo: {},
      nodeList: [],
      vmTypeList: [],
      policyList: [],
      channelInfo: {},
      type: '',
      policyDialog: false,
      policy: {},
      editDialog: false,
      editForm: {
        nodeId: '',
        id: ''
      },
      columns: 10,
      rows: '',
      transform: 'translateX(0px)',
      chooseGoodDialog: false,
      skuForm: {
        pageIndex: 1,
        pageSize: 10,
        skuName: null
      },
      skuTotalPage: 0,
      skuList: [],
      currentGood: [],
      top10Dialog: false,
      top10List: [],
      business: {}
    }
  },
  async created() {
    await this.vmSearch()
  },
  methods: {
    query() {
      this.search.pageIndex = 1
      this.vmSearch()
    },
    async vmSearch() {
      const { currentPageRecords, totalCount, totalPage } = await searchVmList({
        ...this.search
      })
      this.totalCount = parseInt(totalCount)
      this.totalPage = +totalPage
      this.tableData = currentPageRecords
    },
    formattedDate(date) {
      const currentDate = new Date(date)
      const year = currentDate.getFullYear()
      const month = ('0' + (currentDate.getMonth() + 1)).slice(-2)
      const day = ('0' + currentDate.getDate()).slice(-2)
      const hours = ('0' + currentDate.getHours()).slice(-2)
      const minutes = ('0' + currentDate.getMinutes()).slice(-2)
      const seconds = ('0' + currentDate.getSeconds()).slice(-2)
      return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
    },
    async showAdd(type) {
      this.addDialog = true
      this.type = type
      const { currentPageRecords } = await searchVmType({
        pageIndex: 1,
        pageSize: 100000
      })
      this.vmTypeList = currentPageRecords
      const res = await searchNode({ pageIndex: 1, pageSize: 100000 })
      this.nodeList = res.currentPageRecords
    },
    addClose() {
      this.addDialog = false
      this.$refs.add.resetFields()
      this.addForm = {
        nodeId: '',
        vmType: '',
        createUserId: this.$store.getters.userId
      }
    },
    async addSubmit() {
      this.$refs.add.validate(async(isOK) => {
        if (isOK) {
          await addVm({ ...this.addForm })
          this.addClose()
          this.vmSearch()
          this.$message.success('新增设备成功')
        }
      })
    },
    handleSelectionChange(val) {
      this.batchForm.innerCodeList = val.map((item) => item.innerCode)
    },
    async showBatch() {
      this.batchDialog = true
      this.policyList = await getPolicyList()
    },
    batchClose() {
      this.batchDialog = false
      this.$refs.batch.resetFields()
      this.batchForm = {
        innerCodeList: [],
        policyId: ''
      }
    },
    async batchSubmit() {
      await applyPolicy({ ...this.batchForm })
      this.batchClose()
      this.vmSearch()
      this.$message.success('修改成功')
    },
    batchOperate() {
      if (this.batchForm.innerCodeList.length) {
        this.showBatch()
      } else {
        this.$message.warning('请勾选售货机')
      }
    },
    async showPolicy(innerCode) {
      const res = await getVmPolicy(innerCode)
      if (res) {
        this.policyDialog = true
        this.policy = res
      } else {
        this.batchForm.innerCodeList = [innerCode]
        this.showBatch()
      }
    },
    policyClose() {
      this.policyDialog = false
    },
    async showEdit(row) {
      const { currentPageRecords } = await searchNode({
        pageIndex: 1,
        pageSize: 100000
      })
      this.nodeList = currentPageRecords
      this.vmInfo = row
      this.editDialog = true
      this.editForm.id = row.id
      this.editForm.nodeId = row.nodeId
    },
    editClose() {
      this.editDialog = false
      this.$refs.edit.resetFields()
      this.editForm = {
        nodeId: '',
        id: ''
      }
    },
    async editSubmit() {
      await editVmNode({ ...this.editForm })
      this.editClose()
      this.vmSearch()
      this.$message.success('修改成功')
    },
    async showChannelInfo(row) {
      this.channelInfoDialog = true
      const res = await getChannelInfo(row.innerCode)
      this.channelInfo = _.chunk(res, 10)
      this.business = row
    },
    channelInfoClose() {
      this.channelInfoDialog = false
    },
    async confirmChannel() {
      await updateChannel({ innerCode: this.business.innerCode, channelList: _.flatten(this.channelInfo) })
      this.channelInfoClose()
    },
    slider(val) {
      this.transform = `translateX(${val})`
    },
    async addChannel(index, ind) {
      this.chooseGoodDialog = true
      this.getSkuList()
      this.currentGood = [index, ind]
      this.$message.success('添加成功')
    },
    async getSkuList() {
      const { currentPageRecords, totalPage	 } = await searchSku({ ...this.skuForm })
      this.skuList = currentPageRecords.map(item => {
        item.isShow = false
        return item
      })
      this.skuTotalPage = +totalPage
    },
    delChannel(index, ind) {
      this.$nextTick(() => {
        this.channelInfo[index][ind].sku = null
        this.channelInfo[index][ind].skuId = '0'
      })
      this.$message.success('删除成功')
    },
    chooseGoodClose() {
      this.chooseGoodDialog = false
      this.skuForm = {
        pageIndex: 1,
        pageSize: 10,
        skuName: null
      }
      this.currentGood = []
    },
    prevPage() {
      if (this.skuForm.pageIndex > 1) {
        this.skuForm.pageIndex--
      }
      this.getSkuList()
    },
    nextPage() {
      if (this.skuForm.pageIndex < this.skuTotalPage) {
        this.skuForm.pageIndex++
      }
      this.getSkuList()
    },
    chooseGood(index) {
      this.skuList.forEach(item => {
        item.isShow = false
      })
      this.skuList[index].isShow = true
    },
    queryGood() {
      this.skuForm.pageIndex = 1
      this.getSkuList()
    },
    confirmChoose() {
      const res = this.skuList.find(item => item.isShow)
      this.channelInfo[this.currentGood[0]][this.currentGood[1]].skuId = res.skuId
      this.channelInfo[this.currentGood[0]][this.currentGood[1]].sku = res
      this.chooseGoodClose()
    },
    showTop10() {
      this.top10Dialog = true
      this.getTop10List()
    },
    async getTop10List() {
      this.top10List = await getBusinessTop10(this.business.businessId)
    },
    top10Close() {
      this.top10Dialog = false
    },
    confirmTop10() {
      this.channelInfo[0].forEach((item, index) => {
        this.top10List[index].skuImage = this.top10List[index].image
        item.sku = this.top10List[index]
      })
      this.top10Close()
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/common.scss";
</style>
